/**
 * 数据验证中间件
 */
const Joi = require('joi');
const { useModel } = require('../../model/index')


exports.registValidator = async (ctx, next) => {
    const scheme = Joi.object({
        account: Joi.string().min(3).max(10).required(),
        password: Joi.string().required(),
        email: Joi.string().email().required(),
        phone: Joi.string().required()
    })
    const validata = scheme.validate(ctx.request.body)
    if (validata.error) {
        ctx.throw(400, validata.error)
    }

    if (await useModel.findOne({ account: ctx.request.body.account })) {
        ctx.throw(400, '账号已存在')
    }
    if (await useModel.findOne({ email: ctx.request.body.email })) {
        ctx.throw(400, '邮箱已存在')
    }
    if (await useModel.findOne({ phone: ctx.request.body.phone })) {
        ctx.throw(400, '手机已存在')
    }
    await next()
}

exports.loginValidator = async (ctx, next) => {

    const scheme = Joi.object({
        account: Joi.string().min(3).max(10).required(),
        password: Joi.string().required()
    })
    const validata = scheme.validate(ctx.request.body)
    if (validata.error) {
        ctx.throw(400, validata.error)
    }

    if (!await useModel.findOne({ account: ctx.request.body.account, password: ctx.request.body.password })) {
        ctx.status = (400)
        ctx.body = {
            error: 1,
            msg: '账号不存在获取密码错误'
        }
        return
    }

    await next()
}


